package com.fastCms.business.frame.busi.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fastCms.business.frame.constant.ResultCodeConst;
import com.fastCms.business.frame.enums.UserTypeEnum;
import com.fastCms.business.frame.enums.ValidateCodeSceneEnum;
import com.fastCms.business.frame.busi.RedisUserModelManager;
import com.fastCms.business.frame.busi.UserManageService;
import com.fastCms.business.frame.busi.ValidateManageService;
import com.fastCms.business.frame.manage.UserManage;
import com.fastCms.business.frame.pojo.UserModel;
import com.fastCms.business.frame.pojo.entity.User;
import com.fastCms.business.frame.pojo.po.*;
import com.fastCms.business.frame.pojo.vo.UserInfoVO;
import com.fastCms.business.frame.response.ApiResponse;
import com.fastCms.business.frame.response.ResponseUtil;
import com.fastCms.business.frame.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
@Transactional
@Slf4j
public class UserManageServiceImpl implements UserManageService {

    @Autowired
    private ValidateManageService validateManageService;

    @Autowired
    private UserService userServiceImpl;

    @Autowired
    private RedisUserModelManager redisUserModelManager;

    @Override
    public ApiResponse login(UserLoginUserPO param, HttpServletRequest request) {
        Integer checkType = param.getCheckType();
        User user = null;
        //手机验证码登录
        if (checkType == 1) {
            String phone = param.getPhone();
            String validateCode = param.getValidateCode();
            if (StringUtils.isBlank(phone)) {
                return ResponseUtil.fail(ResultCodeConst.PARAM_NULL, "手机号码不能为空!");
            }
            if (StringUtils.isBlank(validateCode)) {
                return ResponseUtil.fail(ResultCodeConst.PARAM_NULL, "验证码不能为空!");
            }
            //验证码校验
            ValidateCodeCheckPO validityCodeCheckPO = ValidateCodeCheckPO.builder().validateCode(validateCode).phone(phone).scene(ValidateCodeSceneEnum.LOGIN.getType()).build();
            ApiResponse<Boolean> checkResult = validateManageService.checkSmsValidateCode(validityCodeCheckPO);
            if (checkResult != null && !Objects.equals(checkResult.getCode(), ResultCodeConst.SUCCESS_CODE)) {
                return checkResult;
            }
            user = userServiceImpl.findByPhone(phone);
            if (null == user) {
                return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, "该用户手机号码不存在!");
            }
            //用户名密码登录
        } else if (checkType == 2) {
            String username = param.getUsername();
            String password = param.getPassword();
            if (StringUtils.isBlank(username)) {
                return ResponseUtil.fail(ResultCodeConst.PARAM_NULL, "用户名不能为空!");
            }
            if (StringUtils.isBlank(password)) {
                return ResponseUtil.fail(ResultCodeConst.PARAM_NULL, "密码不能为空!");
            }
            user = userServiceImpl.findByUsername(username);
            if (null == user) {
                return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, "该用户手机号码不存在!");
            }
            if (!password.equals(user.getPassword())) {
                return ResponseUtil.fail(ResultCodeConst.USER.USER_OR_PWD_ERROR, ResultCodeConst.USER.USER_OR_PWD_ERROR_MSG);
            }
        }
        //4.验证用户状态
        if (null != user.getStatus() && user.getStatus() != 1) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_STATUS_ERROR, ResultCodeConst.USER.USER_STATUS_ERROR_MSG);
        }

        //TODO 上线时改成加密
        //String password = new Md5Hash(userInfo.getPassword(), CommonConst.USER_MANAGER.PWD_PRIVATE_KEY, 1024).toBase64();

        //用户模型
        String token = redisUserModelManager.createToken(UserTypeEnum.USER, user.getId());
        UserModel userModel = new UserModel();
        userModel.setToken(token);
        userModel.setUsername(user.getUsername());
        BeanUtils.copyProperties(user, userModel);
        redisUserModelManager.saveRedisToken(UserTypeEnum.USER, userModel);
        return ResponseUtil.success(userModel);

    }

    @Override
    public ApiResponse<Boolean> register(UserRegisterUserPO param) {
        String phone = param.getPhone();
        User user = userServiceImpl.findByPhone(phone);
        if (null != user) {
            return ResponseUtil.fail(ResultCodeConst.USER.USER_NOT_EXIST, "该用户手机号码不存在!");
        }
        user = new User();
        BeanUtils.copyProperties(param, user);
        userServiceImpl.save(user);
        return ResponseUtil.success(true);
    }

    @Override
    public ApiResponse registerCheck(ValidateCodeCheckPO param, HttpServletRequest request) {
        //先校验手机号有没有被注册
        String phone = param.getPhone();
        User user = userServiceImpl.findByPhone(phone);
        if (null != user) {
            return ResponseUtil.fail(ResultCodeConst.USER.PHONE_BE_REGISTER, ResultCodeConst.USER.PHONE_BE_REGISTER_MGS);
        }
        ApiResponse<Boolean> checkResult = validateManageService.checkSmsValidateCode(param);
        if (checkResult != null && !Objects.equals(checkResult.getCode(), ResultCodeConst.SUCCESS_CODE)) {
            return checkResult;
        }
        return ResponseUtil.success(true);
    }


    @Override
    public ApiResponse<UserInfoVO> selfUserInfo() {
        String userId = UserManage.getUserId();
        User user = userServiceImpl.findById(userId);
        if (user == null) {
            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtil.copyProperties(user, userInfoVO);
        return ResponseUtil.success(userInfoVO);
    }

    @Override
    public ApiResponse infoByUserId(String userId) {
        User user = userServiceImpl.findById(userId);
        if (user == null) {
            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtil.copyProperties(user, userInfoVO);
        return ResponseUtil.success(userInfoVO);
    }

    @Override
    public ApiResponse<Boolean> perfectInfo(UserPrefectInfoPO param) {
        String userId = UserManage.getUserId();
        User user = userServiceImpl.findById(userId);
        if (user == null) {
            return ResponseUtil.fail(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }
        BeanUtils.copyProperties(param, user);
        userServiceImpl.updateById(user);
        return ResponseUtil.success(true);
    }

    @Override
    public ApiResponse<Boolean> logout() {
        String userId = UserManage.getUserId();
        if (StringUtils.isNotBlank(userId)) {
            redisUserModelManager.deleteToken(UserTypeEnum.USER, userId);
        }
        // 组装返回数据
        return ResponseUtil.success(true);
    }

    @Override
    public ApiResponse wxUserRegister(WxUserRegisterPO wxUserRegisterPO, HttpServletRequest request) {
        return null;
    }

    @Override
    public ApiResponse wxGetCode(UserLoginUserPO userLoginUserPO, HttpServletRequest request) {
        return null;
    }

}
